<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}单位`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="单位编码" prop="unitCode">
        <el-input v-model="drawerProps.row!.unitCode" placeholder="请填写单位编码" clearable></el-input>
      </el-form-item>
      <el-form-item label="单位名称" prop="unitName">
        <el-input v-model="drawerProps.row!.unitName" placeholder="请填写单位名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="单位符号" prop="unitSymbol">
        <el-input v-model="drawerProps.row!.unitSymbol" placeholder="请填写单位符号" clearable></el-input>
      </el-form-item>
      <el-form-item label="单位类型" prop="unitType">
        <el-select v-model="drawerProps.row!.unitType" placeholder="请选择单位类型" clearable filterable @change="handleUnitTypeChange">
          <el-option label="数量" value="数量"></el-option>
          <el-option label="重量" value="重量"></el-option>
          <el-option label="长度" value="长度"></el-option>
          <el-option label="面积" value="面积"></el-option>
          <el-option label="体积" value="体积"></el-option>
          <el-option label="时间" value="时间"></el-option>
          <el-option label="温度" value="温度"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="基础单位" prop="isBaseUnit">
        <el-radio-group v-model="drawerProps.row!.isBaseUnit" @change="handleBaseUnitChange">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
        <div class="form-tip">
          <el-text size="small" type="info">基础单位是该类型下的标准单位，其他单位通过换算系数与基础单位进行转换</el-text>
        </div>
      </el-form-item>
      <el-form-item label="换算系数" prop="conversionFactor">
        <el-input-number
          v-model="drawerProps.row!.conversionFactor"
          :precision="4"
          :step="0.1"
          :min="0"
          placeholder="请填写换算系数"
          style="width: 100%"
        ></el-input-number>
      </el-form-item>
      <el-form-item 
        label="基本单位" 
        prop="baseUnitId" 
        v-show="drawerProps.row!.isBaseUnit === 0"
      >
        <el-select
          v-model="drawerProps.row!.baseUnitId"
          placeholder="请选择基本单位"
          clearable
          filterable
          :loading="baseUnitLoading"
          :disabled="!drawerProps.row!.unitType"
        >
          <el-option
            v-for="unit in baseUnitOptions"
            :key="unit.id"
            :label="`${unit.unitName}(${unit.unitCode})`"
            :value="unit.id"
          ></el-option>
        </el-select>
        <div class="form-tip" v-if="!drawerProps.row!.unitType">
          <el-text size="small" type="warning">请先选择单位类型</el-text>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="drawerProps.row!.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="drawerProps.row!.description"
          type="textarea"
          :rows="3"
          placeholder="请填写描述"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UnitDrawer">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { UnitManage } from "@/api/interface";
import { createUnit, updateUnit, getBaseUnits, getBaseUnitsByType } from "@/api/modules/unitManage";

const rules = reactive({
  unitCode: [{ required: true, message: "请填写单位编码", trigger: "blur" }],
  unitName: [{ required: true, message: "请填写单位名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<UnitManage.ResUnitList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 基本单位选项
const baseUnitOptions = ref<UnitManage.ResUnitList[]>([]);
const baseUnitLoading = ref(false);

// 搜索基本单位
const searchBaseUnits = async (query: string) => {
  if (query) {
    baseUnitLoading.value = true;
    try {
      const { data } = await getBaseUnits();
      baseUnitOptions.value = data.filter((unit: UnitManage.ResUnitList) => 
        unit.unitName.includes(query) || unit.unitCode.includes(query)
      );
    } catch (error) {
      console.error("搜索基本单位失败:", error);
    } finally {
      baseUnitLoading.value = false;
    }
  } else {
    baseUnitOptions.value = [];
  }
};

// 加载基础单位选项
const loadBaseUnits = async () => {
  try {
    // 如果选择了单位类型，则根据类型加载基础单位
    if (drawerProps.value.row.unitType) {
      const { data } = await getBaseUnitsByType(drawerProps.value.row.unitType);
      baseUnitOptions.value = data;
    } else {
      // 否则加载所有基础单位
      const { data } = await getBaseUnits();
      baseUnitOptions.value = data;
    }
  } catch (error) {
    console.error("加载基础单位失败:", error);
  }
};

// 单位类型变化处理
const handleUnitTypeChange = (unitType: string) => {
  // 清空基本单位选择
  drawerProps.value.row.baseUnitId = undefined;
  // 重新加载对应类型的基础单位
  if (unitType) {
    loadBaseUnitsByType(unitType);
  } else {
    baseUnitOptions.value = [];
  }
};

// 根据单位类型加载基础单位
const loadBaseUnitsByType = async (unitType: string) => {
  try {
    const { data } = await getBaseUnitsByType(unitType);
    baseUnitOptions.value = data;
  } catch (error) {
    console.error("根据类型加载基础单位失败:", error);
  }
};

// 基础单位变化处理
const handleBaseUnitChange = (isBaseUnit: number) => {
  if (isBaseUnit === 1) {
    // 如果设置为基础单位，清空基本单位ID和换算系数设为1
    drawerProps.value.row.baseUnitId = undefined;
    drawerProps.value.row.conversionFactor = 1.0000;
  } else {
    // 如果不是基础单位，需要选择基本单位
    if (drawerProps.value.row.unitType) {
      loadBaseUnitsByType(drawerProps.value.row.unitType);
    }
  }
};

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  
  // 设置默认值
  if (drawerProps.value.title === "新增") {
    if (drawerProps.value.row.status === undefined) {
      drawerProps.value.row.status = 1;
    }
    if (drawerProps.value.row.conversionFactor === undefined) {
      drawerProps.value.row.conversionFactor = 1.0000;
    }
    if (drawerProps.value.row.isBaseUnit === undefined) {
      drawerProps.value.row.isBaseUnit = 0; // 默认不是基础单位
    }
  }
  
  // 加载基本单位选项
  loadBaseUnits();
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const api = drawerProps.value.title === "新增" ? createUnit : updateUnit;
      await api(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}单位成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error(`${drawerProps.value.title}单位失败:`, error);
    }
  });
};

onMounted(() => {
  loadBaseUnits();
});

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.form-tip {
  margin-top: 5px;
  
  .el-text {
    line-height: 1.2;
  }
}

.el-form-item {
  margin-bottom: 20px;
}

.el-drawer__body {
  padding: 20px;
}
</style>